import json
import os

class TComponentManager:
    def __init__(self):
        self.version="component-2025"
        self.components={}
        self.settings = {}
        self.rootPath=""
    def setSettings(self , dictSettings):
        self.settings = dictSettings
    def loadSettings(self , fileName):
        try:
            settings = self.settings
            if( os.path.exists(fileName)):
                with open( fileName , 'r' , encoding='utf-8') as f :
                    settings = json.load(f)
            self.setSettings(settings)
            for sk in self.settings['components'].keys():
                if sk in self.components.keys():
                    self.components[sk].settings = self.settings['components'][sk]
                    self.components[sk].doOnSetSettings()
        except Exception as er:
            print(er)
    def getComponentActionResult(self , compCode , action , params):
        res = {
            "status": 0 ,# -1:compCode error ; -2:action error,
            "acResult": None
        }
        try:
            if compCode in self.components.keys():
                comp = self.components[compCode]
                if action in comp.handlers.keys():
                    res = comp.handlers[action](**params)
                else:
                    res['status'] = -2
            else:
                res['status'] = -1
        except Exception as er:
            res['status'] = -3
            res['errmsg'] = er.args
            print(er)
        return  res
    def getAbsPath(self , pathName):
        res= pathName
        try:
            if pathName[0:2]=='./':
                res = os.path.join( self.rootPath , pathName[2:])
            else:
                res = os.path.abspath(pathName)
        except Exception as er:
            print(er)
        return  res
print('import component manager.')
componentManager = TComponentManager()